package projectmanagement.web;

import java.util.List;

import org.springframework.validation.Errors;

import projectmanagement.model.Person;
import projectmanagement.model.dao.PersonDao;

public class EnterPersonValidator implements
org.springframework.validation.Validator{
	
	private PersonDao personManager;
	
	public boolean supports(Class clazz) {
		return clazz.equals(Person.class);
	}

	public void validate(Object command, Errors errors) {
		Person person = (Person) command;
		if (person == null)
			return;

		String name = person.getName();
		String surname = person.getSurname();
		String username = person.getUsername();
		String password = person.getPassword();
		
		if (surname == null || surname.trim().length() == 0){
			errors.reject("error.person.surname.required");
		}
		
		if (username == null || username.trim().length() == 0){
			errors.reject("error.person.username.required");
		}
		
		if (password == null || password.trim().length() == 0){
			errors.reject("error.person.password.required");
		}
		
		if (checkSymbols(name) || checkSymbols(surname) || checkSymbols(username) || checkSymbols(password)){
			errors.reject("error.task.illegal.character");
		}
		
		List<Person> persons = personManager.getPersonList();
		for (Person p: persons){
			if(p.getUsername().equals(username)){
				errors.reject("error.person.username.exists");
			}
		}
	}

	public PersonDao getPersonManager() {
		return personManager;
	}

	public void setPersonManager(PersonDao personManager) {
		this.personManager = personManager;
	}
	
	private boolean checkSymbols(String s){
		if(s.contains(">") || s.contains("<") || s.contains("javascript")){
			return true;
		}
		return false;
	}
	
}
